package com.bruceliu.controller;

import com.bruceliu.bean.User;
import com.bruceliu.service.UserService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: RestaurantSystem
 * @BelongsPackage: com.bruceliu.controller
 * @Author: bruceliu
 * @CreateTime: 2020-02-28 15:58
 * @Description: postman
 */
@Controller
@Scope("prototype")
public class UserController {

    @Resource
    UserService userService;

    /**
     * 01-跳转登录页面
     *
     * @return
     */
    @RequestMapping({"/admin", "/login"})
    public String login() {
        System.out.println("111");
        return "login";
    }

    @RequestMapping("/index")
    public String index(){
        return "index"; //模板
    }

    /**
     * 02-执行登录请求
     *
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/user_login")
    public String user_login(String usercode, User user, Model model, HttpSession session) {
        //系统的验证码
        String checkcode = (String) session.getAttribute("checkcode");
        if (checkcode.equalsIgnoreCase(usercode)) {
            System.out.println("表单接收的参数是:" + user);
            User loginUser = userService.login(user);
            if (loginUser != null) {
                session.setAttribute("loginUser", loginUser);
                System.out.println("登录用户是：" + loginUser);
                return "redirect:index";
            } else {
                model.addAttribute("message", "账号或密码错误!");
                return "login";
            }
        }else{
            model.addAttribute("message", "用户输入验证码错误!");
            return "login";
        }
    }

    /**
     * 02-用户注销
     * @return
     */
    @RequestMapping("/user_logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
